<!--
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-28 09:51:46
 * @LastEditTime: 2019-08-31 16:01:51
 * @LastEditors: Please set LastEditors
 -->
<template>
  <div class="app">
    <!-- 左侧树结构 -->
    <div class="tree">
      <el-input placeholder="输入关键字进行过滤" v-model="filterText"></el-input>
      <el-tree
        :load="loadChilds"
        :data="sourceData"
        :props="treeProps"
        node-key="id"
        lazy
        :filter-node-method="filterNode"
        :expand-on-click-node="false"
        :render-content="renderContent"
        ref="tree"
      ></el-tree>
    </div>

    <!-- 右侧数据显示 -->
    <div class="data">
      <div class="list-item"></div>
    </div>
    <!-- <div>{{toData}}</div> -->
  </div>
</template>
<script>
export default {
  props: {
    getDataUrl:{
      type:String,
      default:'http://yapi.devops.erp.ocj.com.cn/mock/219/api/bom/category/CategoryQueryFacade/queryTreeList'
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      filterText: "",
      childData:[],
      sourceData: [
        {
          id: 1,
          name: "一级 1",
          checked: false,
          childs: [
            {
              id: 4,
              name: "二级 1-1",
              checked: false,
              childs: [
                {
                  id: 9,
                  name: "三级 1-1-1",
                  checked: false
                },
                {
                  id: 10,
                  name: "三级 1-1-2",
                  checked: false
                }
              ]
            }
          ]
        },
        {
          id: 2,
          name: "一级 2",
          checked: false,
          childs: [
            {
              id: 5,
              name: "二级 2-1",
              checked: false
            },
            {
              id: 6,
              name: "二级 2-2",
              checked: false
            }
          ]
        },
        {
          id: 11,
          name: "一级 4",
          checked: false,
          childs: [
            {
              id: 12,
              name: "二级 4-1",
              checked: false
            },
            {
              id: 13,
              name: "二级 4-2",
              checked: false
            }
          ]
        }
      ],
      toData: [], //所勾选的数据对象
      toDataString: [], //转换之后的数据
      treeProps: {
        label: "name", // 指定节点标签为节点对象的某个属性值
        children: "children", // 指定子树为节点对象的某个属性值
        isLeaf: (data, node) => {
          if (data.leafYn == 1) {
            return false;
          }
          return true;
        } // 是否为叶子节点
      }
    };
  },
  created() {
    let params = {
      url:this.getDataUrl,
      data: {
        parentId: ""
      }
    };
    ocj.post({
      url: params.url,
      data: params.data,
      success: res => {
        for (let i = 0; i < res.length; i++) {
          if (!res[i].checked) {
            res[i].checked = false;
          }
        }
        console.log(res);
        this.sourceData = res;
      }
    });
  },
  methods: {
    //选中复选框
    change(val, data, node) {
      //val 选中的状态（true 选中，false 取消选中）,data：该节点下的节点（包含子节点） node：所有节点（包含parent）
      let currentId;
      data.checked = val;
      let result = [];
      let _arr;
      this.hideChildren(data, val);
      if (val) {
        //判断是否包含子节点，是则清空所有子节点数据并隐藏
        if (data.children) {
          this.removeAllChildreNode(data);
        }
        //执行选中的逻辑，增加数据到目标数组
        _arr = this.getParentData(node, result).reverse();
        let arr = this.toData;
        arr.push(_arr);
        this.toData = arr;

        this.$emit("handleGetValChild", arr);
      } else {
        //取消勾选逻辑，删除目标数组数据
        this.removeFromData(data.id);
      }
    },
    //展开子节点方法
    loadChilds(node, resolve) {
      console.log('展开子节点：',node);
      if (node.level === 0) {
        return resolve([]);
      }
      // if (node.level > 1) return resolve([]);
      // if (node.level === 1) {
        // 二级节点
        this.getChildrenNode(node, resolve);
      // }
    },
    //加载子节点数据
    getChildrenNode(node, resolve) {
      let categoryId = node.data.id;
      let params = {
        url:
          "http://yapi.devops.erp.ocj.com.cn/mock/219/api/bom/category/CategoryQueryFacade/queryTreeList",
        data: {
          parentId: categoryId.id
        }
      };
      ocj.post({
        url: params.url,
        data: params.data,
        success: res => {
          console.log(res);
          if (res.length == 0) {
            alert("数据拉取失败，请刷新再试");
          }
          for (let i = 0; i < res.length; i++) {
            if (!res[i].checked) {
              res[i].checked = false;
            }
          }
          this.childData=res;
          this.addNodeToParent(categoryId,this.sourceData,resolve)
          // resolve(res);
        }
      });
    },
    //选择父节点隐藏所以子节点
    hideChildren(node, val) {
      if (node.children) {
        node.children.map(m => {
          this.$set(m, "hide", val);
          m.checked = false;
          this.hideChildren(m, val);
        });
      }
      return node;
    },
    //给父节点添加子节点
    addNodeToParent(id, list,resolve) {
      list &&
        list.map(m => {
          if (id === m.id) {
            this.$set(m, "children", this.childData);
            // m.children=this.childData
            resolve([])
          }

          if (m.children) {
            this.addNodeToParent(id, m.children,resolve);
          }
        });
    },
    //勾选父节点，清空所有子节点的值
    removeAllChildreNode(node) {
      this.removeFromData(node.id);
    },
    addToData(item) {
      this.toData.push(item);
    },
    //删除/取消勾选 的数据对象
    removeFromData(dataId) {
      for (let i = 0; i < this.toData.length; i++) {
        this.toData[i].forEach(current => {
          if (dataId === current.id) {
            this.toData.splice(i, 1);
            this.$emit("handleGetValChild", this.toData);
            this.removeFromData(dataId);
          }
        });
      }
    },
    //根据所选择的元素组成数据对象
    getParentData(node, result) {
      let {
          data: { id, name, value },
          parent
        } = node,
        newObj = {};
      newObj = { id, name, value };
      result.push(newObj);
      if (parent.parent !== null) {
        this.getParentData(parent, result);
      } else {
        return result;
      }
      return result;

      result;
    },
    //判断是否是父级节点
    isParentNode(node) {
      return !!node.children;
    },

    renderContent(h, { node, data, store }) {
      let checkDom = null;
      if (!data.hide) {
        checkDom = (
          <div>
            {data.checked}
            <el-checkbox
              on-input={val => this.change(val, data, node)}
              value={data.checked}
            ></el-checkbox>
          </div>
        );
      }
      return (
        <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
          <span>
            <span>{node.label}</span>
          </span>
          <span>{checkDom}</span>
        </span>
      );
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    //查找取消选中的节点
    removeFromIndex(index) {
      let _length = this.toData[index].length - 1;
      let _id = this.toData[index][_length].id;
      this.removeFromData(_id);
      this.changeCheckboxStatus(_id, this.sourceData);
    },
    //取消选中删除的节点
    changeCheckboxStatus(id, list) {
      list &&
        list.map(m => {
          if (id === m.id) {
            this.$set(m, "checked", false);
          }

          if (m.children) {
            this.changeCheckboxStatus(id, m.children);
          }
        });
    }
  }
};
</script>
<style>
.tree {
  width: 300px;
}
</style>